﻿using System.ServiceProcess;
using System.Threading;

namespace Adventure.Service
{
    /// <summary>
    /// Windows service to start the Adventure server.
    /// </summary>
    public partial class AdventureService : ServiceBase
    {
        #region Fields

        /// <summary>
        /// Main Thread of the server.
        /// </summary>
        private Thread _mainThread;

        /// <summary>
        /// Should the main thread be running?
        /// </summary>
        private bool _running;

        #endregion

        /// <summary>
        /// Creates a new instance of AdventureService.
        /// </summary>
        public AdventureService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// OnStart Event.
        /// </summary>
        /// <param name="args">Start Arguments.</param>
        protected override void OnStart(string[] args)
        {
            // Start the main thread.
            _mainThread = new Thread(Run);
            _mainThread.Start();
        }

        /// <summary>
        /// OnStop Event.
        /// </summary>
        protected override void OnStop()
        {
            // Set signal that the main thread should stop.
            _running = false;

            // Wait for the main thread to end.
            int counter = 0;
            while (counter < 10 && _mainThread.ThreadState != ThreadState.Stopped)
            {
                // Wait one second.
                counter++;
                Thread.Sleep(1000);
            }

            if (_mainThread.ThreadState != ThreadState.Stopped)
            {
                // Unable to stop main thread on normal way.
                // TODO! Need a way to handle this!

                // Abort the main thread
                _mainThread.Abort();
            }
        }

        /// <summary>
        /// Main thread of the server.
        /// </summary>
        public void Run()
        {
            // Set the mainThread to the current thread if it is still null.
            if (_mainThread == null)
                _mainThread = Thread.CurrentThread;

            // Main loop of the service.
            _running = true;
            while (_running)
            {
                // TODO

                // Sleep a little.
                Thread.Sleep(100);
            }
        }
    }
}
